#include <iostream>
#include <cstdio>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string>
#include <cstring>

#define N 2
#define BUFFSIZE 1024

using namespace std;

void Writer(int wfd);  // child
void Reader(int rfd);  // father

int main()
{
    int pipefd[N] = {0};
    int n = pipe(pipefd);
    if (n < 0)  return 1;
    //cout << "pipefd[0]: " << pipefd[0] << ", pipefd[1]: " << pipefd[1] << endl;

    // father --> read | child --> write
    pid_t id = fork();
    if (id < 0) 
    {
        perror("fork()");
        return 2;
    }
    if (id == 0)
    {
        // child
        // 子进程关闭管道读取
        close(pipefd[0]);

        // IPC code  write
        Writer(pipefd[1]);

        close(pipefd[1]);
        exit(0);
    }

    // father
    // 父进程关闭管道写入
    close(pipefd[1]);

    // IPC code  read
    Reader(pipefd[0]);

    pid_t rid = waitpid(id, nullptr, 0);
    if (rid < 0)  return 3;

    close(pipefd[0]);
    sleep(5);
    return 0;
}

void Writer(int wfd)
{
    string s = "hello, I am child";
    pid_t self = getpid();
    int number = 0;

    char buffer[BUFFSIZE];
    while (true)
    {
        sleep(1);

        // 构建发送字符串
        buffer[0] = 0;  // 0 == '\0' 字符串清空，意为提醒该数组被当作字符串使用
        snprintf(buffer, sizeof(buffer), "%s-%d-%d", s.c_str(), self, number++);
        //cout << buffer << endl;
        
        // 发送/写入给父进程, system call
        write(wfd, buffer, strlen(buffer));
        if (number == 8)  break;
    }
}

void Reader(int rfd)
{
    char buffer[BUFFSIZE];

    while (true)
    {
        buffer[0] = 0;
        // system call
        ssize_t n = read(rfd, buffer, sizeof(buffer));

        if (n > 0) {
            buffer[n] = 0;  //0 == '\0'
            cout << "father get a message[" << "]# " << buffer << endl;
        }
        else if (n == 0) {
            cout << "father read file done!" << endl;
            break;
        }
        else perror("read()");
    }
}